var path = require('path');
var log4js = require('log4js');
var express = require('express');

var pkg = require('../package.json');
var response = require("../app/response");

var ejs = require('ejs');
ejs.open = '{{';
ejs.close = '}}';
require('./db');

module.exports = function(app, config) {

	app.use(express.compress({
		filter: function(req, res) {
			return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
		},
		level: 9
	}));
	app.use(express.static(path.join(config.root, 'public')));
	app.use(express.favicon(path.join(config.root, 'public','favicon.ico')));
	app.use(express.logger('dev'));
	app.set('views', path.join(config.root, 'views'));
	app.set('view engine', 'ejs');
	app.use(log4js.connectLogger(require('./logs').access(), {level:log4js.levels.INFO}));
	app.set('showStackError', true);
	//app.use(express.bodyParser({ keepExtensions: true, uploadDir: config.uploadPath}));
    app.use(express.json());
    app.use(express.urlencoded());
	app.use(express.methodOverride());
	app.use(express.cookieParser('foreveross-cow.com'));
    app.use(express.session());
	app.use(app.router);
	app.disable('x-powered-by');
	app.use(function(req, res, next) {
		res.locals.pkg = pkg;
		next();
	});

	// =============================handle 404 and 500===========================//
	app.use(function(err, req, res, next) {
		if (err.message && (~err.message.indexOf('not found') || (~err.message.indexOf('Cast to ObjectId failed')))) {
			return next();
		}
		console.error(err.stack);
		if (req.is('application/json')) {
			response.server500(res);	
		} else {
			res.status(500).render('500', {
				error: err.stack
			});
		}
	});

	// =============================assume 404 since no middleware responded===========================//
	app.use(function(req, res, next) {
		if (req.is('application/json')) {
			response.server404(res);	
		} else {
			res.status(404).render('404', {
				url: req.originalUrl,
				error: 'Not found'
			});
		}
	});
};
